#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include "FMODSystem.h"
#include "FMODSound.h"
#include "FMODDspBpm.h"
#include "BPMReader.h"

#define DELTA_FREQUENCY 100
#define DELTA_ERROR     5000

using namespace std;

int main()
{
    try
    {
		FMODSystem sys;
		sys.init();

		printf("Loading song...\n");

		//FMODSound sound(&sys, "always.mp3", true);
		FMODSound sound(&sys, "mrpitiful.mp3", true);

		printf("Song loaded...\n");

		printf("Sound lenght: %u\n", sound.getLength());

        FMODDspBpm dsp(&sys, &sound);

        float songBpm = dsp.getBpm();
        printf("BPM Detected: %f\n", songBpm);

		sound.play();

		BPMReader bpmreader;

		float initialFreq = sound.getFrequency();
		float currentFreq = initialFreq;
		float targetFreq = initialFreq;

		printf("Frequency: %f\n", initialFreq);

        bool exit = false;

		while(!exit)
		{
		    if(kbhit())
		    {
                char input = getch();

                switch(input)
                {
                    case 'q':
                        exit = true;
                    break;
                    case '-':
                        sound.setFrequency(sound.getFrequency() - DELTA_FREQUENCY);
                    break;
                    case '+':
                        sound.setFrequency(sound.getFrequency() + DELTA_FREQUENCY);
                    break;
                    case ' ':
						bpmreader.tap();

						float ratio = bpmreader.getBpm() / songBpm;

						targetFreq = ratio * initialFreq;

                        /// Slowly (or not) slide to the input rythm
                        if(abs((int)(targetFreq - currentFreq)) > DELTA_FREQUENCY * 2)
                        {
                            if(targetFreq > currentFreq) currentFreq += DELTA_FREQUENCY;
                            if(targetFreq < currentFreq) currentFreq -= DELTA_FREQUENCY;
                            /// sound.setFrequency(currentFreq);
                            printf("Current: %f \n", currentFreq);
                        }
                    break;
                }

                printf("BPM Input: %f\n", bpmreader.getBpm());
                printf("Ratio: %f\n", bpmreader.getBpm() / songBpm);
		    }
		}

		return 0;
    }
    catch(Exception e)
    {
		printf("Error: %s\n", e.getMessage());
	}
}
